package cn.kgc.vue.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.kgc.vue.common.ResponseResult;
import cn.kgc.vue.common.ResponseStatus;
import cn.kgc.vue.dto.RolePageDTO;
import cn.kgc.vue.entity.Permission;
import cn.kgc.vue.entity.Role;
import cn.kgc.vue.entity.RolePers;
import cn.kgc.vue.entity.UserRole;
import cn.kgc.vue.form.RolePermissionForm;
import cn.kgc.vue.mapper.PermissionMapper;
import cn.kgc.vue.mapper.RoleMapper;
import cn.kgc.vue.mapper.RolePersMapper;
import cn.kgc.vue.mapper.UserRoleMapper;
import cn.kgc.vue.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService{

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RolePersMapper rolePersMapper;

    @Autowired
    private PermissionMapper permissionMapper;


    @Override
    public ResponseResult getRolePage(RolePageDTO rolePageDTO) {

        ResponseResult responseResult = new ResponseResult();
        String roleName = rolePageDTO.getRoleName();
        LambdaQueryWrapper<Role> lambda = new QueryWrapper<Role>().lambda();
        // 判定是否传递了角色名字 实现动态sql
        lambda.eq(StringUtils.isNotBlank(roleName),Role::getRoleCh,roleName)
            .orderByDesc(Role::getRoleId);

        Page<Role> rolePage = new Page<>(rolePageDTO.getCurrentPage(), rolePageDTO.getLimit());
        roleMapper.selectPage(rolePage,lambda);

        HashMap<String, Object> result = new HashMap<>();
        // 获取分页数据  当前页
        result.put("currentPageData", rolePage.getRecords());
        // 数据的总条数
        result.put("total",rolePage.getTotal());

        responseResult.success(ResponseStatus.SUCCESS,result);
        return responseResult;
    }

    @Override
    public ResponseResult deleteById(Integer id) {
        ResponseResult responseResult = new ResponseResult();
        // 1.根据角色id 查询user_role
        LambdaQueryWrapper<UserRole> lambda = new QueryWrapper<UserRole>().lambda();
        lambda.eq(UserRole::getRoleId,id);
        List<UserRole> userRoles = userRoleMapper.selectList(lambda);
        if (ObjectUtil.isNotEmpty(userRoles)){
            // 角色被占用 不能删除
            responseResult.fail(ResponseStatus.ROLE_USED);
            return  responseResult;
        }
        //2.删除角色信息
        roleMapper.deleteById(id);

        //3.删除 role_permission 中角色相关数据
        LambdaQueryWrapper<RolePers> lambda1 = new QueryWrapper<RolePers>().lambda();
        lambda1.eq(RolePers::getRoleId,id);
        rolePersMapper.delete(lambda1);

        responseResult.success();
        return responseResult;
    }

    @Override
    public ResponseResult addPermission(RolePermissionForm rolePermissionForm) {

        ResponseResult responseResult = new ResponseResult();
        // 1.根据角色id  删除原有权限
        Integer roleId = rolePermissionForm.getRoleId();
        LambdaQueryWrapper<RolePers> lambda = new QueryWrapper<RolePers>().lambda();
        lambda.eq(RolePers::getRoleId,roleId);
        rolePersMapper.delete(lambda);

        //2.将最新的权限信息写入  role_permission
        List<Integer> ids = rolePermissionForm.getIds();
        ids.forEach(pid->{
            RolePers rolePers = new RolePers();
            rolePers.setRoleId(roleId);
            rolePers.setPerId(pid);
            rolePersMapper.insert(rolePers);
        });
        responseResult.success();
        return responseResult;
    }

    @Override
    public ResponseResult getRolePermission(Integer id) {

        ResponseResult responseResult = new ResponseResult();
        LambdaQueryWrapper<RolePers> lambda = new QueryWrapper<RolePers>().lambda();
        lambda.eq(RolePers::getRoleId,id);
        List<Integer> pIds = rolePersMapper.selectList(lambda).stream().map(rp -> rp.getPerId()).collect(Collectors.toList());

        if(pIds.size()==0){
            //int[] pids = {};
            responseResult.success(ResponseStatus.SUCCESS,new ArrayList<>());
            return responseResult;
        }

        // 筛选 按钮级别的权限
        LambdaQueryWrapper<Permission> lambda1 = new QueryWrapper<Permission>().lambda();
        lambda1.in(Permission::getId,pIds)
                .eq(Permission::getIsMenu,2);

        List<Integer> btnPermissionIds = permissionMapper.selectList(lambda1).stream().map(p -> p.getId()).collect(Collectors.toList());
        responseResult.success(ResponseStatus.SUCCESS,btnPermissionIds);

        return responseResult;
    }
}




